from typing import Any, List, Optional
from bson import ObjectId
from backend.models.common import PyObjectId
from pydantic import BaseModel, Field


INSTANCE_COLLECTION = "dwf_instance"


class DwfInstanceBase(BaseModel):
    name: str = Field(..., description="实例名称，必须唯一")
    description: Optional[str] = Field(None, description="实例描述")
    host: str = Field(..., description="实例host")
    modeler_port: int = Field(..., description="实例建模服务端口号")
    app_port: int = Field(..., description="实例应用服务端口号")
    username: str = Field(..., description="登录用户名")
    password: str = Field(..., description="登录密码")

    class Config:
        # 允许 orm 模式，以便与数据库对象映射
        from_attributes = True
        # 提供示例数据，将显示在API文档中
        json_schema_extra = {
            "example": {
                "name": "dev-instance-01",
                "description": "Development instance for testing.",
                "host": "192.168.1.100",
                "modeler_port": 9090,
                "app_port": 8080,
                "username": "admin",
                "password": "secure_password"
            }
        }


# 用于创建实例时接收数据的模型 (与Base模型相同)
class CreateDwfInstanceModel(DwfInstanceBase):
    pass


# 用于更新实例时接收数据的模型，所有字段都是可选的
class UpdateDwfInstanceModel(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    host: Optional[str] = None
    modeler_port: Optional[int] = None
    app_port: Optional[int] = None
    username: Optional[str] = None
    password: Optional[str] = None

    class Config:
        json_schema_extra = {
            "example": {
                "description": "Updated description for the instance.",
                "host": "192.168.1.101"
            }
        }


# 从数据库返回数据时使用的模型，包含了id字段
class DwfInstanceInDB(DwfInstanceBase):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")

    class Config:
        # 允许通过字段名(field name)或别名(alias)进行赋值
        validate_by_name = True
        # 必须开启，否则无法正确处理ObjectId
        json_encoders = {ObjectId: str}


class PaginatedDwfInstanceResponse(BaseModel):
    """用于分页查询的响应模型"""
    total_count: int = Field(..., description="匹配查询条件的总实例数")
    items: List[DwfInstanceInDB] = Field(..., description="当前页的实例列表")